/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.exam;


import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class second {
    private static int num; // 成员变量
    @AnonymousAccess
    @PostMapping("/uploadScores")
    public String uploadScores(@RequestParam("scoreFile") MultipartFile scoreFile,
                               @RequestParam("num") int nu
                             ) throws IOException {
        this.num=nu;
        String filePath = "C:/a/name1.xlsx";
        String sheetName = "Sheet1"; // 要写入内容的工作表名称


        File scoreSheetFile = convertMultiPartFileToFile(scoreFile);
     //   File nameListSheetFile = convertMultiPartFileToFile(nameListFile);

        Workbook scoreWorkbook = WorkbookFactory.create(scoreSheetFile);
        Sheet scoreSheet = scoreWorkbook.getSheetAt(0);

        Workbook nameListWorkbook = WorkbookFactory.create(new FileInputStream(new File(filePath)));
        Sheet nameListSheet = nameListWorkbook.getSheet(sheetName);

        Map<String, Double> scoresMap = extractScores(scoreSheet); // 提取得分表的姓名和得分
        updateNameList(nameListSheet, scoresMap); // 更新名单表的得分列

        try (FileOutputStream outputStream = new FileOutputStream(new File(filePath))) {
            nameListWorkbook.write(outputStream);
            // 无需手动关闭Workbook，try-with-resources会自动关闭资源


        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常
        } finally {
            try {
                nameListWorkbook.close(); // 关闭Workbook
            } catch (IOException e) {
                e.printStackTrace();
                // 处理关闭Workbook时的异常
            }
        }
        return null; // 如果发生异常，返回null或适当的错误提示
    }
    private static Map<String, Double> extractScores(Sheet scoreSheet) {
        Map<String, Double> scoresMap = new HashMap<>();

        for (int i = scoreSheet.getFirstRowNum() + 1; i <= scoreSheet.getLastRowNum(); i++) {
            Row row = scoreSheet.getRow(i);
            if (row != null) {
                Cell nameCell = row.getCell(0);
                Cell scoreCell = row.getCell(2);

                if (nameCell != null && nameCell.getCellType() == CellType.STRING
                        && scoreCell != null && scoreCell.getCellType() == CellType.NUMERIC) {

                    String name = nameCell.getStringCellValue();
                    double score = scoreCell.getNumericCellValue();

                    scoresMap.put(name, score);
                }
            }
        }

        return scoresMap;
    }

    private static void updateNameList(Sheet nameListSheet, Map<String, Double> scoresMap) {

        for (int i = nameListSheet.getFirstRowNum()+1; i <= nameListSheet.getLastRowNum(); i++) {
            Row row = nameListSheet.getRow(i);
            if (row != null) {
                Cell nameCell = row.getCell(0);

                if (nameCell != null && nameCell.getCellType() == CellType.STRING) {
                    String name = nameCell.getStringCellValue();

                    if (scoresMap.containsKey(name)) {
                        double score = scoresMap.get(name);

                        Cell scoreCell = row.createCell(num-1);
                        scoreCell.setCellValue(score);
                    }
                    else{
                        double score=0;
                        Cell scoreCell = row.createCell(num-1);
                        scoreCell.setCellValue(score);
                    }
                }
            }
        }
    }

    private File convertMultiPartFileToFile(MultipartFile multipartFile) throws IOException {
        File file = new File(multipartFile.getOriginalFilename());
        try (OutputStream os = new FileOutputStream(file)) {
            os.write(multipartFile.getBytes());
        }
        return file;
    }



}
